<template>
  <view class='productList'>
    <uv-notify ref="notify" message="success" type="success"></uv-notify>
    <uv-sticky :offsetTop="0" :customNavHeight="0" bgColor="#fff">
      <view class="titleName">{{ statusNavProperties.title }}</view>
    </uv-sticky>
    <view class="body-page">
      <uv-gap height="10" bgColor=""></uv-gap>
      <uv-form labelWidth="80" labelPosition="left" :model="form" :rules="rules" ref="form">

        <uv-form-item required label="目的地" prop="destination" borderBottom>
          <uv-input border="bottom" placeholder="如实填写" v-model="form.destination">
            <template v-slot:prefix>
              <uv-text
                  @click="selectUseAddress(1)"
                  text="常用地址"
                  margin="0 3px 0 0"
                  type="tips"
              ></uv-text>
            </template>
          </uv-input>
        </uv-form-item>

        <uv-form-item required label="始发地" prop="actionAddress" borderBottom>
          <uv-input border="bottom" placeholder="如实填写" v-model="form.actionAddress">
            <template v-slot:prefix>
              <uv-text
                  @click="selectUseAddress(2)"
                  text="常用地址"
                  margin="0 3px 0 0"
                  type="tips"
              ></uv-text>
            </template>
          </uv-input>
        </uv-form-item>
        <uv-form-item required label="酬劳" prop="amount" borderBottom>
          <view style="width: 100%">
            <view>
              <uv-input border="bottom" type="digit" @blur="amountInputChange" v-model="form.amount" placeholder="酬劳"
                        prefixIcon="https://minio.thisforyou.cn:1443/test/金额.png"
              >
              </uv-input>
            </view>
            <view style="display: flex;justify-content: center;margin-top: 20rpx;flex-wrap: wrap">
              <uv-button @click="useAmount(1)" style="margin: 20rpx" :color="themConfig.theme.color" text="¥1" plain
                         size="small"></uv-button>
              <uv-button @click="useAmount(2)" style="margin: 20rpx" :color="themConfig.theme.color" text="¥2" plain
                         size="small"></uv-button>
              <uv-button @click="useAmount(3.5)" style="margin: 20rpx" :color="themConfig.theme.color" text="¥3.5" plain
                         size="small"></uv-button>
              <uv-button @click="useAmount(4.5)" style="margin: 20rpx" :color="themConfig.theme.color" text="¥4.5" plain
                         size="small"></uv-button>
              <uv-button @click="useAmount(7)" style="margin: 20rpx" :color="themConfig.theme.color" text="¥7" plain
                         size="small"></uv-button>
              <uv-button @click="useAmount(9)" style="margin: 20rpx" :color="themConfig.theme.color" text="¥9" plain
                         size="small"></uv-button>
              <uv-button @click="useAmount(10)" style="margin: 20rpx" :color="themConfig.theme.color" text="¥10" plain
                         size="small"></uv-button>
              <uv-button @click="useAmount(15)" style="margin: 20rpx" :color="themConfig.theme.color" text="¥15" plain
                         size="small"></uv-button>
            </view>
          </view>
        </uv-form-item>

        <uv-form-item required label="过期时间" prop="expireTime" borderBottom>
          <uv-datetime-picker :minDate="datetimePicker.minDate" :formatter="datePickerformatter" :maxDate="datetimePicker.maxDate"
                              ref="expireTime" v-model="datetimePicker.value" mode="datetime" @confirm="checkExpireDate($event,'expireTime')">
          </uv-datetime-picker>
          <view style="width: 100%">
            <view>
              <uv-input @focus="openDatePick('expireTime')" readonly border="bottom" placeholder="无人接单到期自动取消订单" v-model="form.expireTime">
              </uv-input>
            </view>
            <view style="display: flex;justify-content: center;margin-top: 20rpx;flex-wrap: wrap">
              <uv-button @click="setExpireTime(0.5)" style="margin: 20rpx" :color="themConfig.theme.color" text="0.5小时" plain
                         size="small"></uv-button>
              <uv-button @click="setExpireTime(1)" style="margin: 20rpx" :color="themConfig.theme.color" text="1小时" plain
                         size="small"></uv-button>
              <uv-button @click="setExpireTime(3)" style="margin: 20rpx" :color="themConfig.theme.color" text="3小时" plain
                         size="small"></uv-button>
              <uv-button @click="setExpireTime(5)" style="margin: 20rpx" :color="themConfig.theme.color" text="5小时" plain
                         size="small"></uv-button>
              <uv-button @click="setExpireTime(10)" style="margin: 20rpx" :color="themConfig.theme.color" text="10小时" plain
                         size="small"></uv-button>
              <uv-button @click="setExpireTime(24)" style="margin: 20rpx" :color="themConfig.theme.color" text="24小时" plain
                         size="small"></uv-button>
            </view>
          </view>


        </uv-form-item>

        <uv-form-item required label="任务说明" prop="content" borderBottom>
          <uv-textarea v-model="form.content" placeholder="备注说明，所有人可见"></uv-textarea>
        </uv-form-item>

        <uv-form-item label="敏感信息" prop="sensitiveContent" borderBottom>
          <uv-textarea v-model="form.sensitiveContent" placeholder="敏感信息，例如 取件码；接单后，双方可见"></uv-textarea>
        </uv-form-item>

        <uv-form-item label="辅助照片（公开）" prop="photos" borderBottom>
          <UvUpload @uploadChange="uploadSuccess"/>
        </uv-form-item>


        <uv-form-item  label="配送时间️" prop="deliveryTimeStart"
                      borderBottom>
          <uv-datetime-picker :minDate="datetimePicker.minDate" :formatter="datePickerformatter" :maxDate="datetimePicker.maxDate"
                              ref="deliveryTimeStart" v-model="datetimePicker.deliveryTimeStart" mode="datetime"
                              @confirm="checkExpireDate($event,'deliveryTimeStart')">
          </uv-datetime-picker>

          <uv-input inputAlign="left" @focus="openDatePick('deliveryTimeStart')" border="bottom" v-model="form.deliveryTimeStart"
                    placeholder="开始时间"></uv-input>

        </uv-form-item>

        <uv-form-item  label="配送时间️" prop="deliveryTimeEnd"
                      borderBottom>
          <uv-datetime-picker :minDate="datetimePicker.minDate" :formatter="datePickerformatter" :maxDate="datetimePicker.maxDate"
                              ref="deliveryTimeEnd" v-model="datetimePicker.deliveryTimeEnd" mode="datetime"
                              @confirm="checkExpireDate($event,'deliveryTimeEnd')">
          </uv-datetime-picker>

          <uv-input inputAlign="left" @focus="openDatePick('deliveryTimeEnd')" border="bottom" v-model="form.deliveryTimeEnd"
                    placeholder="结束时间"></uv-input>
        </uv-form-item>


        <uv-form-item label="接单后审核" prop="needAudit" borderBottom>
          <uv-switch :activeColor="themConfig.theme.subColor" v-model="form.needAudit"></uv-switch>
        </uv-form-item>

        <uv-form-item required label="联系电话" prop="phone" borderBottom>
          <uv-input border="bottom" v-model="form.phone" placeholder="如实填写,方便接单人联系"></uv-input>
        </uv-form-item>
        <uv-gap height="20"/>
<!--        <view class="agreement">-->
<!--          <view>-->
<!--            <uv-checkbox-group v-model="isReadAggreement">-->
<!--              <uv-checkbox-->
<!--                  shape="circle"-->
<!--                  @change="agreementReadClick"-->
<!--                  :activeColor="themConfig.theme.subColor"-->
<!--                  :customStyle="{marginBottom: '8px'}"-->
<!--                  v-for="(item, index) in [{name:'',value: 1}]"-->
<!--                  :key="index" :label="item.name"-->
<!--                  :name="item.value"-->
<!--              ></uv-checkbox>-->
<!--            </uv-checkbox-group>-->

<!--          </view>-->
<!--          <view class="agreementText">-->
<!--            <text :style="{-->
<!--                    color:themConfig.theme.subColor-->
<!--                  }" @click="readAgreement">请阅读协议声明-->
<!--            </text>-->
<!--          </view>-->
<!--        </view>-->

      </uv-form>

<!--      <view class="tip">-->
<!--        <view class="icon">-->
<!--          <image src="https://minio.thisforyou.cn:1443/test/灯泡.png" style="width: 30px;height: 30px"/>-->
<!--        </view>-->
<!--        <view class="content" :style="{-->
<!--                  color:themConfig.theme.subColor-->
<!--                }">-->
<!--          重要物品，请慎重下单-->
<!--        </view>-->
<!--      </view>-->
      <uv-gap height="80" bgColor=""></uv-gap>
    </view>
    <view class="button">
      <view class="money">
        <text style="color: #303133">支付跑腿酬金</text>
        <text :style="{
        color: themConfig.theme.subColor,
        paddingLeft: '10px',
        'font-size':'18px'
      }">¥{{ form.amount }}
        </text>
      </view>
      <view class="submitBtn">
        <uv-button text="点击提交订单" :disabled="btnDisabled" @click="submit"
                   :color="'linear-gradient(to right,' +themConfig.theme.subColor+', '+themConfig.theme.color+')'"></uv-button>
      </view>
    </view>
    <uv-picker ref="picker" :columns="useAddress" @confirm="useAddressConfirm"></uv-picker>
  </view>
</template>
<script>
import OrderList from '@/components/school/orderList';
import UvUpload from '@/components/school/uv-upload';
import {mapGetters} from "vuex";
import * as OrderApi from '@/api/school/order.js';

import diyJson from '@/config/diy.js';
import * as MemerApi from '@/api/member/user.js';
import {
  AgreementEnum,
} from '@/utils/dict.js';
import * as TaskInfoApi from '@/api/school/taskInfo.js';

export default {
  computed: mapGetters(['uid','schoolId', 'userInfo', 'shareInfo']),
  components: {
    UvUpload,
    OrderList,
  },
  data() {
    return {

      datetimePicker: {
        value: '',
        minDate: Number(new Date()),
        maxDate: Number(new Date().setHours(new Date().getMinutes() + 24)),
        deliveryTimeStart:'',
        deliveryTimeEnd:'',
      },

      rules: {
        'content': {
          type: 'string',
          required: true,
          message: '请填内容',
          trigger: ['blur', 'change']
        }, 'expireTime': {
          type: 'string',
          required: true,
          message: '请选择',
          trigger: ['blur', 'change']
        },
        'actionAddress': {
          type: 'string',
          required: true,
          message: '请填始发地',
          trigger: ['blur', 'change']
        }, 'destination': {
          type: 'string',
          required: true,
          message: '请填始目的地',
          trigger: ['blur', 'change']
        }, 'amount': {
          type: 'number',
          required: true,
          message: '金额不能为空',
          trigger: ['blur', 'change']
        }, 'phone': {
          type: 'number',
          required: true,
          message: '联系电话不能为空',
          trigger: ['blur', 'change']
        },
      },

      btnDisabled: false,

      themConfig: diyJson.commonStyle,

      pageBody: {
        scrollTop: 0,
      },

      statusNavProperties: { // 筛选条件
        title: "订单池",
        setStyle: {
          bgColor: "white",
          enableBack: true,
          titleColor: "rgba(100, 101, 102)",
          titleStyle: {}
        }
      },

      isReadAggreement: [],

      photos: [],

      form: {
        isRead: true,
        taskId: '',
        needAudit: false,
        expireTime: '',
        amount: 2,
        content: '',
        sensitiveContent: '',
        actionAddress: '',
        destination: '',
        photos: [],
        deliveryTimeStart: '',
        deliveryTimeEnd: '',
        shareCode: ''
      },
      // 1=目的地，2=始发地
      useAddressType: 2,
      useAddress: [],
      useAddressData: [],
    };
  },

  onLoad: function (options) {
    let p = options.params;
    if (p) {
      let params = JSON.parse(decodeURIComponent(p));
      // console.log("params", params)
      this.statusNavProperties.title = params.titleName;
      this.form.taskId = params.taskId;
      this.form.taskCode = params.taskCode;

      // 获取详情
      this.getTaskDetail(this.form.taskCode,this.schoolId);
      this.getUseAddressData();
    }
  },

  onShow() {
    if (!this.form['phone']){
      this.form['phone'] = this.userInfo.phone;
    }

  },
  mounted() {

  },

  methods: {
     getTaskDetail(taskCode, schoolId) {
       TaskInfoApi.getTaskByCode(taskCode, schoolId).then(res => {
         this.form.taskId = res.data.id;
      });
    },

    // 打开时间选择框
    openDatePick(field) {
      this.$refs[field].open();
    },

    // 选择时间回调
    checkExpireDate(e,field) {
      // console.log("时间",new Date(e.value));
      // console.log("时间",field);
      var date = new Date(e.value); // 转换为Date对象

      // 获取年月日时分秒
      var year = date.getFullYear();
      var month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的
      var day = ('0' + date.getDate()).slice(-2);
      var hours = ('0' + date.getHours()).slice(-2);
      var minutes = ('0' + date.getMinutes()).slice(-2);
      // var seconds = ('0' + date.getSeconds()).slice(-2);

      // 组合成 yyyy-mm-dd HH:mm:ss 格式
      if (field===undefined || field==='expireTime'){
        this.form.expireTime = `${year}-${month}-${day} ${hours}:${minutes}:00`;
      }else {
        this.form[field] = `${year}-${month}-${day} ${hours}:${minutes}:00`;
      }
    },

    datePickerformatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      }
      if (type === 'month') {
        return `${value}月`
      }
      if (type === 'day') {
        return `${value}日`
      }

      if (type === 'hour') {
        return `${value}时`
      }

      if (type === 'minute') {
        return `${value}分`
      }
      return value
    },

    // 快捷选择时间
    setExpireTime(v) {
      let d = new Date();
      if (v < 1) {
        d.setMinutes(d.getMinutes() + (v * 60));
      } else {
        d.setHours(d.getHours() + v);
      }
      this.checkExpireDate({value: Number(d)})
    },

    clearShareCode() {
      this.shareInfo = null;
      this.$store.commit('SET_SHARE_CODE', null)
    },

    // 获取常用地址
    getUseAddressData() {
      MemerApi.getUseAddress({}).then(res => {
        this.useAddressData = res.data;
        if (res.data.length){
          for (let i = 0; i < res.data.length; i++) {
            let item = res.data[i];
            if (item.type===1){
              let addr = item.addressVos[0];
              this.form.destination=addr.detail;
            }

            if (item.type===2){
              let addr = item.addressVos[0];
              this.form.actionAddress=addr.detail;
            }
          }
        }
      })
    },

    // 选择常用地址
    selectUseAddress(type) {
      this.useAddressType = type;
      for (let i = 0; i < this.useAddressData.length; i++) {
        let item = this.useAddressData[i];
        if (item.type === type) {
          let arr = [];
          for (let j = 0; j < item.addressVos.length; j++) {
            arr.push(item.addressVos[j].detail)
          }
          this.useAddress = [arr];
          this.$refs.picker.open();
          return;
        }
      }
    },

    // 确定常用地址
    useAddressConfirm(e) {
      console.log("常用地址", e);
      if (this.useAddressType === 2) {
        this.form.actionAddress = e.value[0];
      } else {
        this.form.destination = e.value[0];
      }
    },

    // 输入金额变化
    amountInputChange(e) {
      this.$nextTick(() => {
        this.form.amount = parseFloat(e).toFixed(2);
      });
      console.log("amount", this.form.amount)
    },

    // 选择常用金额
    useAmount(e) {
      this.form.amount = e;
    },

    agreementReadClick(e) {
      this.form.isRead = e;
    },

    /**
     * 上传结果
     * @param array [
     *   {
     *     images:[{'url':''}],
     *     params:'',
     *   }
     * ]
     */
    uploadSuccess(array) {
      console.log("array", array)
      let photos = [];
      for (let i = 0; i < array.images.length; i++) {
        photos.push(array.images[i].url);
      }
      this.form.photos = photos;
      console.log("form", this.form)
    },

    // 提交表单
    submit() {
      if (!this.form.isRead) {
        this.$refs.notify.show({
          message: '请阅读协议声明',
          type: 'warning',
          duration: 1000,
          safeAreaInsetTop: true
        });
        return;
      }
      console.log("form", this.form)
      // 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
      this.$refs.form.validate().then(res => {
        this.btnDisabled = true;

        // 邀请码
        if (this.shareInfo !== undefined && this.shareInfo !== null && this.shareInfo !== '') {
          this.form['inviteCode'] = JSON.parse(this.shareInfo).code
        }

        OrderApi.createOrder({...this.form,num:1, schoolId: this.schoolId}).then(res => {
          let data = res.data;

          let params = {
            outTradeNo: data.outTradeNo,
            amount: data.amount,
            body: this.statusNavProperties.title,
            payScene: data.payScene
          }

          this.$refs.notify.show({
            message: '正在跳转支付',
            type: 'success',
            duration: 1000,
            safeAreaInsetTop: true
          });

          this.$store.commit('SET_JUMP_INFO', params);

          setTimeout(() => {
            this.btnDisabled = false;
            uni.navigateTo({
              url: `/pages/school/pay/index?params=${encodeURIComponent(JSON.stringify(params))}`
            })
          }, 1000)
        }).catch(e => {
          this.btnDisabled = false;
        })
      }).catch(errors => {
        this.btnDisabled = false;
        console.log("eee", errors)
        // this.$refs.notify.show({
        //   message: '请将必填项写上',
        //   type: 'warning',
        //   duration: 1000,
        //   safeAreaInsetTop: true
        // });
      })
    },

    readAgreement() {
      uni.navigateTo({
        url: `/pages/users/privacy/index?params=${encodeURIComponent(JSON.stringify(AgreementEnum.pushTask))}`
      })
    },

  },
  onReachBottom() {

  }
}
</script>

<style scoped lang="scss">
.body-page {
  padding: 0 20px;
}

.productList {
  background: #fff;
}

.tip {
  margin-top: 20px;
  display: flex;
  align-items: center;
  border-radius: 10px;
  padding: 20px;
  border: 1px solid #ebebeb;

  .content {
    padding-left: 20px;
  }
}

.agreement {
  margin-top: 30px;
  display: flex;
  justify-content: center;

  .agreementText {
    margin-top: -1px;
  }
}

.button {
  height: 65px;
  width: 100%;
  background: white;
  padding: 10px 20px;
  position: fixed;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-top: 1px solid #ebebeb;
}
.submitBtn{
  width: 50%;
}
.titleName {
  text-align: center;
  font-size: 36rpx;
  padding: 30rpx;
}
</style>
